package com.kangaroo.myhome.controller;

import com.kangaroo.myhome.Exception.CustomException;
import com.kangaroo.myhome.Exception.CustomExceptionType;
import com.kangaroo.myhome.model.FileChunk;
import com.kangaroo.myhome.model.TInspVideo;
import com.kangaroo.myhome.service.impl.TInspBigFileUploadService;
import com.kangaroo.myhome.vo.ResponseModel;
import io.swagger.annotations.Api;
import it.sauronsoftware.jave.MultimediaInfo;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import it.sauronsoftware.jave.Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UploadBigFileController
 * @Description TODO
 * @Author kangaroo
 * @Date 2020/9/6 5:38
 * @Version 1.0
 **/
@RestController
@Api(value = "/bigFileUpload", description = "大文件上传，支持分件分片上传")
@RequestMapping("/bigFileUpload")
public class UploadBigFileController {

    @Value("${file.downPath}")
    private String filePath;

    @Value("${file.downPathTemp}")
    private String filePathTemp;

    @Autowired
    private TInspBigFileUploadService tInspBigFileUploadService;

    @GetMapping(value = "/findAll")
    public ResponseModel findAll(HttpServletRequest request) {
        String name = request.getParameter("subjectId");
        String pageS = request.getParameter("page");
        String rowsS = request.getParameter("rows");
        int page = Integer.parseInt(pageS);
        int rows = Integer.parseInt(rowsS);
        return tInspBigFileUploadService.findAll(name, page, rows);
    }

    @GetMapping(value = "/view")
    public ResponseModel view(HttpServletRequest request) {
        ResponseModel model = new ResponseModel();
        String id = request.getParameter("id");

        TInspVideo tInspVideo = new TInspVideo();
        tInspVideo.setId(id);
        TInspVideo user = tInspBigFileUploadService.view(tInspVideo);
        model.setCode(200);
        model.setMessage("获取成功");
        model.setData(user);
        return model;
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public ResponseModel edit(@RequestBody TInspVideo tInspVideo) {
        return tInspBigFileUploadService.edit(tInspVideo);
    }

    /**
     * 分片上传
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel upload(HttpServletRequest request, FileChunk chunk, String projectId) throws IOException {
        ResponseModel model = new ResponseModel();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            MultipartFile file = chunk.getFile();

            if (file == null) {
                throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "请选择上传的文件");
            }

            Integer chunkNumber = chunk.getChunkNumber();
            if (chunkNumber == null) {
                chunkNumber = 0;
            }
            try {
                File outFile =
                    new File(filePathTemp + File.separator + chunk.getIdentifier(),
                        chunkNumber + ".part");

                /*File outFile =
                        new File(filePathTemp + File.separator + projectId + File.separator + chunk.getIdentifier(),
                                chunkNumber + ".part");*/

                InputStream inputStream = file.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, outFile);
            } catch (IOException e) {

            }

        }

        return model;
    }

    /**
     * 合并所有分片
     */
    @RequestMapping(value = "/merge", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel mergeFile(String identifier, TInspVideo video) throws Exception {
        ResponseModel model = new ResponseModel();
        String filename = video.getName();
        // File.separator + video.getProjectId() +
        File file = new File(filePathTemp +  File.separator + identifier);
        long fileNameSubLong = new Date().getTime();
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                // + video.getProjectId() + File.separator
                String fileName = filePath +  File.separator + fileNameSubLong + filename;
                File partFile = new File(fileName);
                for (int i = 1; i <= files.length; i++) {
                    // File.separator + video.getProjectId() +
                    File s = new File(filePathTemp +  File.separator + identifier,
                            i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(partFile, true);
                    FileUtils.copyFile(s, destTempfos);
                    destTempfos.close();
                }
                FileUtils.deleteDirectory(file);

                File fileAll = new File(fileName);
                Encoder encoder = new Encoder();
                MultimediaInfo info = encoder.getInfo(fileAll);
                long duration = info.getDuration();
                String fileRelativePath = "insp/file/"+ fileNameSubLong + filename;
                video.setName(filename);
                video.setPath(fileRelativePath);
                video.setTimes((int)(duration / 1000));
                // model = tInspBigFileUploadService.edit(video);
                Map map = new HashMap();
                map.put("filePath",fileRelativePath);
                map.put("timeLong",(int)(duration / 1000));
                model.setData(map);
            }
        }

        return model;
    }

    public static void main(String[] args) throws Exception {
        File fileAll = new File("F:/IDEA_WORKSPACE/myhome/inspFile/1/test.mp4");
        Encoder encoder = new Encoder();
        MultimediaInfo info = encoder.getInfo(fileAll);
        long duration = info.getDuration();
        System.out.println("时长：" + duration);
    }

    @PostMapping(value = "/delete")
    public ResponseModel delete(HttpServletRequest request) {
        String id = request.getParameter("id");
        TInspVideo tInspVideo = new TInspVideo();
        tInspVideo.setId(id);
        tInspBigFileUploadService.delete(tInspVideo);
        ResponseModel model = new ResponseModel();
        model.setCode(200);
        model.setMessage("操作成功");
        return model;
    }

}
